<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>导出功能简单测试</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 40px; 
            line-height: 1.6;
        }
        .test-card { 
            border: 1px solid #ddd; 
            border-radius: 8px; 
            padding: 20px; 
            margin: 20px 0; 
            background: #f9f9f9;
        }
        button { 
            padding: 12px 20px; 
            margin: 8px; 
            background: #007bff; 
            color: white; 
            border: none; 
            border-radius: 4px; 
            cursor: pointer; 
            font-size: 14px;
        }
        button:hover { 
            background: #0056b3; 
        }
        .disabled {
            background: #ccc !important;
            cursor: not-allowed !important;
        }
        #output { 
            background: #f8f9fa; 
            padding: 15px; 
            border-radius: 5px; 
            margin-top: 20px;
            font-family: monospace; 
            font-size: 12px;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .url-display {
            background: #e9ecef;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            font-size: 12px;
            word-break: break-all;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>导出功能测试工具</h1>
    <p>用于测试线索数据导出功能，包括登录和数据导出</p>

    <div class="test-card">
        <h3>步骤1：管理员登录</h3>
        <p>先登录获取访问令牌</p>
        <button id="loginBtn">管理员登录</button>
        <div>状态: <span id="loginStatus">未登录</span></div>
    </div>

    <div class="test-card">
        <h3>步骤2：测试导出接口</h3>
        <p>测试不同的导出方式</p>
        <button id="testDirectBtn" class="disabled">测试直接访问导出URL</button>
        <button id="testApiBtn" class="disabled">测试API调用</button>
        <button id="testDownloadBtn" class="disabled">测试触发下载</button>
        <button id="testSpecificIdsBtn" class="disabled">测试指定ID导出</button>
    </div>

    <div class="test-card">
        <h3>步骤3：测试结果</h3>
        <button id="clearBtn">清除日志</button>
        <div id="output">等待测试...</div>
    </div>

    <script>
        let authToken = '';
        
        function log(message, type = 'info') {
            const output = document.getElementById('output');
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'error' : type === 'success' ? 'success' : 'info';
            output.innerHTML += `<span class="${className}">[${timestamp}] ${message}</span>\n`;
            output.scrollTop = output.scrollHeight;
        }
        
        function clearLog() {
            document.getElementById('output').innerHTML = '';
        }
        
        function updateLoginStatus(isLoggedIn) {
            const status = document.getElementById('loginStatus');
            const buttons = ['testDirectBtn', 'testApiBtn', 'testDownloadBtn', 'testSpecificIdsBtn'];
            
            if (isLoggedIn) {
                status.textContent = '已登录';
                status.style.color = 'green';
                buttons.forEach(btnId => {
                    const btn = document.getElementById(btnId);
                    btn.classList.remove('disabled');
                    btn.disabled = false;
                });
            } else {
                status.textContent = '未登录';
                status.style.color = 'red';
                buttons.forEach(btnId => {
                    const btn = document.getElementById(btnId);
                    btn.classList.add('disabled');
                    btn.disabled = true;
                });
            }
        }
        
        async function testLogin() {
            log('开始测试管理员登录...');
            try {
                const response = await fetch('/api/admin/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: 'admin',
                        password: 'admin123'
                    })
                });
                
                const result = await response.json();
                log(`登录响应状态: ${response.status}`);
                log(`登录响应: ${JSON.stringify(result, null, 2)}`);
                
                if (response.ok && result.data && result.data.token) {
                    authToken = result.data.token;
                    localStorage.setItem('adminToken', authToken);
                    log('登录成功!', 'success');
                    updateLoginStatus(true);
                } else {
                    log(`登录失败: ${result.message}`, 'error');
                    updateLoginStatus(false);
                }
            } catch (error) {
                log(`登录错误: ${error.message}`, 'error');
                updateLoginStatus(false);
            }
        }
        
        async function testDirectAccess() {
            log('测试直接访问导出URL...');
            if (!authToken) {
                log('请先登录!', 'error');
                return;
            }
            
            const exportUrl = `/api/admin/clues/export?format=excel&token=${encodeURIComponent(authToken)}`;
            log('构建的URL:');
            log(exportUrl);
            
            try {
                log('在新窗口中打开导出URL...');
                window.open(exportUrl, '_blank');
                log('已在新窗口中打开，请检查下载是否开始', 'success');
            } catch (error) {
                log(`直接访问失败: ${error.message}`, 'error');
            }
        }
        
        async function testApiCall() {
            log('测试API调用...');
            if (!authToken) {
                log('请先登录!', 'error');
                return;
            }
            
            try {
                const exportUrl = `/api/admin/clues/export?format=excel&token=${encodeURIComponent(authToken)}`;
                log('发送API请求...');
                log(`请求URL: ${exportUrl}`);
                
                const response = await fetch(exportUrl, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                });
                
                log(`API响应状态: ${response.status}`);
                log(`响应Content-Type: ${response.headers.get('content-type')}`);
                log(`响应Content-Disposition: ${response.headers.get('content-disposition')}`);
                
                if (response.ok) {
                    log('API调用成功!', 'success');
                    if (response.headers.get('content-type')?.includes('application/vnd.ms-excel')) {
                        log('返回的是Excel文件格式', 'success');
                    }
                } else {
                    const errorText = await response.text();
                    log(`API调用失败: ${errorText}`, 'error');
                }
            } catch (error) {
                log(`API调用错误: ${error.message}`, 'error');
            }
        }
        
        async function testTriggerDownload() {
            log('测试触发下载...');
            if (!authToken) {
                log('请先登录!', 'error');
                return;
            }
            
            try {
                const exportUrl = `/api/admin/clues/export?format=excel&token=${encodeURIComponent(authToken)}`;
                log('创建下载链接...');
                
                // 方法1：创建隐藏的a标签
                const link = document.createElement('a');
                link.href = exportUrl;
                link.download = `线索导出_${new Date().toISOString().split('T')[0]}.xls`;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                log('已触发下载（方法1：a标签）', 'success');
                
                // 方法2：创建iframe
                setTimeout(() => {
                    const iframe = document.createElement('iframe');
                    iframe.style.display = 'none';
                    iframe.src = exportUrl;
                    document.body.appendChild(iframe);
                    log('已创建iframe（方法2：iframe）', 'success');
                    
                    setTimeout(() => {
                        if (iframe.parentNode) {
                            iframe.parentNode.removeChild(iframe);
                            log('iframe已清理');
                        }
                    }, 5000);
                }, 1000);
                
            } catch (error) {
                log(`触发下载失败: ${error.message}`, 'error');
            }
        }
        
        async function testSpecificIds() {
            log('测试指定ID导出...');
            if (!authToken) {
                log('请先登录!', 'error');
                return;
            }
            
            try {
                // 从你的截图看，有ID为1,2的线索
                const clueIds = '1,2';
                const exportUrl = `/api/admin/clues/export?format=excel&clue_ids=${clueIds}&token=${encodeURIComponent(authToken)}`;
                log(`测试导出指定ID: ${clueIds}`);
                log(`URL: ${exportUrl}`);
                
                // 直接打开下载链接
                const link = document.createElement('a');
                link.href = exportUrl;
                link.download = `指定线索导出_${new Date().toISOString().split('T')[0]}.xls`;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                log('已触发指定ID导出', 'success');
                
            } catch (error) {
                log(`指定ID导出失败: ${error.message}`, 'error');
            }
        }
        
        // 绑定事件
        document.getElementById('loginBtn').addEventListener('click', testLogin);
        document.getElementById('testDirectBtn').addEventListener('click', testDirectAccess);
        document.getElementById('testApiBtn').addEventListener('click', testApiCall);
        document.getElementById('testDownloadBtn').addEventListener('click', testTriggerDownload);
        document.getElementById('testSpecificIdsBtn').addEventListener('click', testSpecificIds);
        document.getElementById('clearBtn').addEventListener('click', clearLog);
        
        // 页面加载时检查是否已有token
        window.addEventListener('load', function() {
            const token = localStorage.getItem('adminToken');
            if (token) {
                authToken = token;
                updateLoginStatus(true);
                log('发现已保存的登录token', 'success');
            } else {
                updateLoginStatus(false);
            }
        });
        
        log('测试页面已加载，请按步骤进行测试');
    </script>
</body>
</html> 